﻿using System.Data.Entity;
using System.Linq;
using WeBlog.Interfaces;
using WeBlog.Models;

namespace WeBlog.Repositories
{
    public class PostRepository : RepositoryBase<Post>
    {        
        public PostRepository(IUnitOfWork unitOfWork) : base( unitOfWork )
        {            
        }        

        public Post FindBySlug(string slug)
        {
            return FindAll().SingleOrDefault(x => x.Slug == slug);
        }

        public override void Remove(Post entity)
        {
            if( entity.Categories != null )
                entity.Categories.Clear();
            
            if( entity.Tags != null )
                entity.Tags.Clear();

            if( entity.PostVisits != null )
                entity.PostVisits.Clear();
            base.Remove(entity);
        }

        public IOrderedQueryable<Post> FeaturedPosts()
        {
            return PublishedPosts().Where(x => x.Featured ).OrderByDescending(x => x.PublishDate);
        }

        public IQueryable<Post> PublishedPosts()
        {
            return Context.DbSet<Post>()
                .Include( x => x.Author )   
                .Include( x => x.Tags )
                .Include( x => x.PostRatings )
                .Include( x => x.Categories )
            .Where(x => x.Published );
        }
    }
}
